package org.learn.java;

import java.awt.Color;

import org.sedgewick.StdDraw;

public class SARW {

	public static void main(String[] args) {
		int L = Integer.parseInt(args[0]); // Limit for Number of Grids
		int T = Integer.parseInt(args[1]); // Number of Trials
		StdDraw.setCanvasSize(800, 800);
		StdDraw.setScale(0, L);
		StdDraw.setPenRadius(0.010);
		StdDraw.setPenColor(Color.BLUE);
		
		for (int N = 1; N <= L; N++) {
			int deadends = 0;
			for (int t = 0; t < T; t++) { // Number of Trials
				int x = N / 2;
				int y = x;
				boolean intersect[][] = new boolean[N][N]; // Grid of N X N
				while (x > 0 && x < N - 1 && y > 0 && y < N - 1) { // Boundary
																	// condition

					intersect[x][y] = true;// check
					// Check for dead end
					if (intersect[x + 1][y] && intersect[x - 1][y]
							&& intersect[x][y + 1] && intersect[x][y - 1]) {
						deadends++;
						break;
					}

					double p = Math.random();
					if (p < 0.25) {
						if (!intersect[x + 1][y])
							x++;
					} else if (p < 0.5) {
						if (!intersect[x - 1][y])
							x--;
					} else if (p < 0.75) {
						if (!intersect[x][y + 1])
							y++;
					} else {
						if (!intersect[x][y - 1])
							y--;
					}
				}
			}

			double de = (100.0 * deadends) / T;		
			
			StdDraw.point(N, de);

			System.out.printf(
					"%6.3f of dead ends out of %d trials for %d X %d Grid\n",
					de, T, N, N);
		}
	}
}
